<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="课程名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

<!--      <el-form-item label="课程学期" prop="term" style="width: 300px">-->
<!--        <el-select v-model="queryParams.term" placeholder="请选择课程学期" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in course_term"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="课时安排" prop="arrangement" style="width: 210px">-->
<!--        <el-select v-model="queryParams.arrangement" placeholder="请选择课时安排" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in course_arrangement"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
        <el-form-item label="老师选择" prop="userId">
            <el-select v-model="queryParams.userId" placeholder="请选择老师" style="width: 200px" >
                <el-option
                        v-for="teacher in teachers"
                        :key="teacher.userId"
                        :label="teacher.userName"
                        :value="teacher.userId"

                />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
<!--      <el-form-item label="开始日期" prop="starttime" label-width="100px">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.starttime"-->
<!--          type="date"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          placeholder="请选择开始日期"-->
<!--                        style="width: 198px"-->
<!--        >-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="结束日期" prop="endtime" label-width="100px">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.endtime"-->
<!--          type="date"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          placeholder="请选择结束日期"-->
<!--                        style="width: 198px">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="星期" prop="courseweek">-->
<!--        <el-select v-model="queryParams.courseweek" placeholder="请选择星期" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in user_week"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->


    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['course:course:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:course:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:course:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="Download"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['course:course:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程名称" align="center" prop="name" />
      <el-table-column label="学时" align="center" prop="hours" />
      <el-table-column label="课程学期" align="center" prop="term">
        <template #default="scope">
          <dict-tag :options="course_term" :value="scope.row.term"/>
        </template>
      </el-table-column>
<!--        years-->
        <el-table-column label="学年" align="center" prop="years">
        </el-table-column>
<!--      <el-table-column label="课时安排" align="center" prop="arrangement">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="course_arrangement" :value="scope.row.arrangement"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="教室" align="center" prop="classroom" />
      <el-table-column label="最大人数" align="center" prop="maxnum" />
      <el-table-column label="图片" align="center" prop="imgs" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imgs" :width="50" :height="50"/>
        </template>
      </el-table-column>
<!--        课程描述-->

      <el-table-column label="开始日期" align="center" prop="starttime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.starttime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endtime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="星期" align="center" prop="courseweek">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="user_week" :value="scope.row.courseweek"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="老师" align="center" prop="teacher.userName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130px">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['course:course:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['course:course:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程设置管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="courseRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程名称"  maxlength="50"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="学时" prop="hours">
          <el-input v-model="form.hours" placeholder="请输入学时" />
        </el-form-item>
        <el-form-item label="学分" prop="credits">
          <el-input v-model="form.credits" placeholder="请输入学分" />
        </el-form-item>
        <el-form-item label="课程学期" prop="term">
          <el-select v-model="form.term" placeholder="请选择课程学期">
            <el-option
              v-for="dict in course_term"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="年份" prop="years">
              <el-select v-model="form.years" placeholder="请选择年份">
                  <el-option
                          v-for="dict in course_years"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                  ></el-option>
              </el-select>
          </el-form-item>
        <el-form-item label="教室" prop="classroom">
      <el-select v-model="form.classroom" placeholder="请选择教室">
              <el-option
                v-for="form in classroomList"
                :key="form.roomname"
                :label="form.roomname"
                :value="form.roomname"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="最大人数" prop="maxnum">
          <el-input v-model="form.maxnum" placeholder="请输入最大人数" />
        </el-form-item>
        <el-form-item label="图片" prop="imgs">
          <image-upload v-model="form.imgs" limit="1"/>
        </el-form-item>
          <el-form-item label="课程描述" prop="coursedesc">
              <el-input
                      type="textarea"
                      v-model="form.coursedesc"
                      placeholder="请输入课程描述"
                      :autosize="{ minRows: 1, maxRows: 4 }"
                      maxlength="200"
                      show-word-limit
              />
          </el-form-item>
        <el-form-item label="开始日期" prop="starttime">
          <el-date-picker clearable
            v-model="form.starttime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endtime">
          <el-date-picker clearable
            v-model="form.endtime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="星期" prop="courseweek">-->
<!--          <el-select v-model="form.courseweek" placeholder="请选择星期">-->
<!--            <el-option-->
<!--              v-for="dict in user_week"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
          <el-form-item label="老师" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择老师">
                  <el-option
                          v-for="teacher in teachers"
                          :key="teacher.userId"
                          :label="teacher.userName"
                          :value="teacher.userId"
                  />
              </el-select>
          </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Course">
import { listCourse, getCourse, delCourse, addCourse, updateCourse,listTeacher,listClassroom } from "@/api/course/course";
import { ref, onMounted } from 'vue';
const { proxy } = getCurrentInstance();
const { course_arrangement, course_term, user_week,course_years } = proxy.useDict('course_arrangement', 'course_term', 'user_week','course_years');

const courseList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const teachers = ref([]);

onMounted(() => {
    loadTeachers();
    loadClassroomList();
});

// 查询所有老师
const loadTeachers = async () => {
    try {
        const response = await listTeacher();
        teachers.value = response.data || []; // 假设response.data是包含老师列表的数组
    } catch (error) {
        console.error('Error fetching teachers:', error);
    }
};
//查询所有教室
const classroomList = ref([]);
const loadClassroomList = async () => {
    try {
        const response = await listClassroom();
        classroomList.value = response.data || []; // 假设response.data是包含教室列表的数组
    } catch (error) {
        console.error('Error fetching classrooms:', error);
    }
};
const validateHours = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请注意,不能为空'));
    } else {
        const numberValue = Number(value);
        if (!Number.isInteger(numberValue) || numberValue.toString().length > 3) {
            callback(new Error('请输入不要超过3位的整数'));
        } else {
            callback();
        }
    }
};
const validateMaxnum = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请注意,不能为空'));
    } else {
        const numberValue = Number(value);
        if (!Number.isInteger(numberValue) || numberValue.toString().length > 5) {
            callback(new Error('请输入不要超过5位的整数'));
        } else {
            callback();
        }
    }
};
// 定义一个通用的validator函数
/*function validateDate(rule, value, callback) {
    if (!value) {
        return callback(new Error('请选择日期'));
    }
    const currentDate = new Date();
    const selectedDate = new Date(value);
    if (selectedDate < currentDate) {
        return callback(new Error('日期不能小于当前日期'));
    }
    callback();
}*/
function validateDate(rule, value, callback) {
    if (!value) {
        return callback(new Error('请选择日期'));
    }

    // 获取当前日期
    const currentDate = new Date();

    // 解析form表单中的years值，假设形式为"2023-2024"
    const years = form.value.years.split('-');
    const endYear = parseInt(years[1], 10);
    const endOfYear = new Date(endYear, 11, 31); // 11代表12月，因为JavaScript的月份是从0开始计数的

    // 检查日期是否小于当前日期
    const selectedDate = new Date(value);
    if (selectedDate < currentDate) {
        return callback(new Error('日期不能小于当前日期'));
    }

    // 检查日期是否大于结束年份的年底
    if (selectedDate > endOfYear) {
        return callback(new Error(`日期不能大于${endYear}年底`));
    }

    callback();
}

const data = reactive({
  form: {
      userId:'',
  },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    name: null,
    hours: null,
    credits: null,
    term: null,
    arrangement: null,
    coursedesc: null,
    classroom: null,
    maxnum: null,
    imgs: null,
    starttime: null,
    endtime: null,
    courseweek: null,
    userId: null,
      teacher: {
        userId: null,
        userName: null
      }

  },
  rules: {
      name: [
          { required: true, message: "课程名称不能为空", trigger: "blur" },
          { min: 3, max: 50, message: '课程名称长度必须在3到50个字符之间', trigger: 'blur' }
      ],
      //    hours只能是数字，最大长度3
      hours: [
          { required: true, message: "学时不能为空", trigger: "blur" },
          { validator: validateHours, trigger: 'blur' }
      ],
      //    credits只能是数字，最大长度2
      credits: [
          { required: true, message: "学分不能为空", trigger: "blur" },
          { validator: validateHours, trigger: 'blur'}
      ],
      maxnum: [
          //    maxnum只能是数字，最大长度10
          { required: true, message: "最大人数不能为空", trigger: "blur" },
          { validator: validateMaxnum, trigger: 'blur' }
      ],
      //    starttime: null,endtime: null, 开始日期要大于当前日期时分秒也算，
      starttime: [
          { required: true, message: "开始日期不能为空", trigger: "blur" },
          { validator: validateDate, trigger: "blur" }
      ],
      endtime: [
          { required: true, message: "结束日期不能为空", trigger: "blur" },
          {
              validator: (rule, value, callback) => {
                  if (!value) {
                      return callback(new Error('请选择结束日期'));
                  }
                  if (!form.value.starttime) {
                      return callback(new Error('开始日期未选择，无法比较结束日期'));
                  }
                  const startTime = new Date(form.value.starttime);
                  const endTime = new Date(value);
                  if (endTime <= startTime) {
                      return callback(new Error('结束日期必须晚于开始日期'));
                  }
                  callback();
              },
              trigger: "blur"
          }
      ],
      userId: [
          { required: true, message: "老师不能为空", trigger: "blur" }
      ],
  }
});



const { queryParams, form, rules } = toRefs(data);

/** 查询课程设置管理列表 */
function getList() {
  loading.value = true;
  listCourse(queryParams.value).then(response => {
    courseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    hours: null,
    credits: null,
    term: null,
    arrangement: null,
    coursedesc: null,
    classroom: null,
    maxnum: null,
    imgs: null,
    starttime: null,
    endtime: null,
    courseweek: null,
    userId: null,
      teacher: {
        userId: null,
        userName: null
      }
  };
  proxy.resetForm("courseRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加课程设置管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCourse(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改课程设置管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["courseRef"].validate(valid => {
    if (valid) {
        console.log('表单验证通过');
      if (form.value.id != null) {
        updateCourse(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCourse(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除课程设置管理编号为"' + _ids + '"的数据项？').then(function() {
    return delCourse(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('course/course/export', {
    ...queryParams.value
  }, `course_${new Date().getTime()}.xlsx`)
}

getList();
</script>
